package org.sgy.mall.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.sgy.mall.dao.impl.OrderDaoImpl;
import org.sgy.mall.dao.impl.ProductDaoImpl;
import org.sgy.mall.model.Cart;
import org.sgy.mall.model.OrderDetail;
import org.sgy.mall.model.OrderInfo;
import org.sgy.mall.model.Page;

public class OrderServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String type = req.getParameter("type");
		if (type.equals("list")) {
			list(req, resp);
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String type = req.getParameter("type");
		if (type.equals("add")) {
			add(req, resp);
		}
	}

	protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 订单信息
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setOrderTime(new Date());
		// 订单明细信息
		List<OrderDetail> detailList = new ArrayList();
		orderInfo.setDetailList(detailList);
		String[] values = req.getParameterValues("productName");
		for (int i = 0; i < values.length; i++) {
			String name = req.getParameterValues("productName")[i];
			String priceStr = req.getParameterValues("price")[i];
			String numStr = req.getParameterValues("num")[i];
			int price = (int) Double.parseDouble(priceStr);
			int num = Integer.parseInt(numStr);

			// 构建detail对象
			OrderDetail detail = new OrderDetail();
			detail.setProductName(name);
			detail.setPrice(price);
			detail.setNum(num);
			detailList.add(detail);
		}
		// 插入数据库
		OrderDaoImpl orderDao = new OrderDaoImpl();
		orderDao.add(orderInfo);
		resp.getWriter().println("提交订单成功");
	}

	protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 获取信息
		OrderDaoImpl orderDao = new OrderDaoImpl();
		List<OrderInfo> list = orderDao.list();
		req.setAttribute("list", list);
		// 分页
		String pageStr = req.getParameter("page");
		String limitStr = req.getParameter("limit");
		int page = 1;
		int limit = 2;
		try {
			page = Integer.parseInt(pageStr);
			limit = Integer.parseInt(limitStr);
		} catch (Exception e) {
		}
		Page page1 = new Page();
		page1.setPage(page);
		page1.setLimit(limit);
		page1.setTotal(list.size());
		req.setAttribute("page", page1);
		req.getRequestDispatcher("/product/orderList.jsp").forward(req, resp);
	}
}
